package com.hange.ymcc.userdetails;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.hange.ymcc.domain.Login;
import com.hange.ymcc.domain.Permission;
import com.hange.ymcc.exception.BusinessException;
import com.hange.ymcc.exception.ErrorCode;
import com.hange.ymcc.service.ILoginService;
import com.hange.ymcc.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private ILoginService loginService;

    @Autowired
    private IPermissionService permissionService;
    @Override
    public UserDetails loadUserByUsername(String username) {
        //先根据用户名查询登录信息
        Wrapper<Login> Wrapper = new EntityWrapper<>();
        Wrapper.eq("username",username);
        Login login = loginService.selectOne(Wrapper);
        if (login == null){
            throw new BusinessException(ErrorCode.NULL_ERROR,"用户不存在");
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        List<Permission> permissions = permissionService.selectPemissionByLoginId(login.getId());
        for (Permission permission : permissions) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(permission.getSn());
            authorities.add(simpleGrantedAuthority);
        }
        Login newLogin = new Login();
        newLogin.setId(login.getId());
        newLogin.setUsername(login.getUsername());
        newLogin.setAvatar(login.getAvatar());

        String jsonString = JSON.toJSONString(newLogin);

        User user = new User(
                jsonString,
                login.getPassword(),
                login.getEnabled(),
                login.getAccountNonExpired(),
                login.getCredentialsNonExpired(),
                login.getAccountNonLocked(),
                 authorities
        );
        return user;
    }
}
